package com.godtree.util.bazhuayu;

import cn.hutool.http.Header;
import cn.hutool.http.HttpUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 获取token
 *
 * @author Lisicheng
 */
public final class TokenTools {

  private static final String URL = "https://dataapi.bazhuayu.com/token";

  private static final String USERNAME = "117779352@qq.com";

  private static final String PASSWORD = "11111111Q";

  private static final Map<String, Object> MAP = new HashMap<>(5);

  private static final Log log = LogFactory.get();

  static {
    MAP.put("username", USERNAME);
    MAP.put("password", PASSWORD);
    MAP.put("grant_type", "password");
  }

  public synchronized static String getToken() {
    if (isExpires()) {
      log.info("token信息过期，重新获取token。");
      return login();
    }
    return Constant.TOKEN;
  }

  /**
   * 登录获取token
   *
   * @return if 包含error信息，return null。则返回正常tokne
   */
  private static String login() {
    String body = HttpUtil
        .createPost(URL)
        .header(Header.CONTENT_TYPE, "application/x-www-form-urlencoded")
        .form(MAP).execute()
        .body();
    JSONObject json = JSON.parseObject(body);
    if (json.containsKey(Constant.MSG_ERROR)) {
      return null;
    }

    log.info("token获取成功。");

    Constant.EXPIRES_TIME = LocalDateTime.now().plusSeconds(json.getIntValue("expires_in"));
    return Constant.TOKEN = "bearer " + json.getString("access_token");
  }

  /**
   * 判断token是否过期
   *
   * @return 过期 true
   */
  private static boolean isExpires() {
    Duration duration = Duration.between(LocalDateTime.now(), Constant.EXPIRES_TIME);
    // 剩余时间（秒）小于10秒时，判定为过期
    return duration.toMillis() / 1000 < 10;
  }
}
